package org.truenewx.tnxjee.webmvc.security.web.authentication;

import java.io.IOException;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.truenewx.tnxjee.core.util.SpringUtil;
import org.truenewx.tnxjee.model.spec.user.security.UserSpecificDetails;
import org.truenewx.tnxjee.webmvc.security.core.UserSpecificDetailsConverter;
import org.truenewx.tnxjee.webmvc.security.util.SecurityUtil;

public class UserSpecificDetailsConvertFilter implements Filter {

    private final UserSpecificDetailsConverter converter;

    public UserSpecificDetailsConvertFilter(ApplicationContext context) {
        this.converter = SpringUtil.getFirstBeanByClass(context, UserSpecificDetailsConverter.class);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (this.converter != null) {
            UserSpecificDetails<?> userDetails = SecurityUtil.getAuthorizedUserDetails();
            if (userDetails != null) {
                SecurityUtil.setAuthorizedUserDetails(this.converter.convert(userDetails), (HttpServletRequest) request,
                        (HttpServletResponse) response);
            }
        }
        chain.doFilter(request, response);
    }

}
